package com.dmx.adi;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class ADIUtil {

	private static Log log = LogFactory.getLog(ADIUtil.class);

	private final static String separator = System.getProperty("file.separator");

	private final static String METADATASTORE = "metadata_store";

	public ADIUtil() {
		//
	}

	public final static StringBuffer download(String addr) {

		try {
			URL url = new URL(addr);

			URLConnection conn = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			StringBuffer ret = new StringBuffer();
			while ((line = in.readLine()) != null)
				ret.append(line);
			in.close();
			return ret;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}

	}

	public final static byte[] download2(String addr) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		// DataOutputStream o=new DataOutputStream(out);
		byte[] bytes = null;
		InputStream in = null;
		try {
			URL url = new URL(addr);

			URLConnection conn = url.openConnection();
			conn.setReadTimeout(30000);
			conn.setConnectTimeout(30000);
			in = conn.getInputStream();
			byte[] buffer = new byte[1024];
			int l;
			while ((l = in.read(buffer)) >= 0) {
				out.write(buffer, 0, l);
			}

			bytes = out.toByteArray();

			out.close();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return bytes;
	}

	public final static void saveXmlFile(StringBuffer _buffer, String _name) {
		try {
			FileWriter fw = new FileWriter(System.getProperty("user.dir") + separator + METADATASTORE + separator + _name + ".xml");

			fw.write(_buffer.toString());
			fw.close();
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public final static void saveXmlFile(byte[] _buffer, String _name) {
		try {
			FileOutputStream fw = new FileOutputStream(System.getProperty("user.dir") + separator + METADATASTORE + separator + _name + ".xml");

			fw.write(_buffer);
			fw.close();
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

}
